﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.Practices.Unity;
using MiniStock.Infrastructure;

namespace MiniStock.BusinessLogic.EventProcessor.EventRepository
{
    public class EventDbRepository : IRepository<EventProcessorEventData>
    {
        [Dependency]
        public EventDbContext DataContext { get; set; }

        public bool BatchCommit { get; set; }

        public EventProcessorEventData Add(EventProcessorEventData item)
        {
            try {
            DataContext.Events.Add(item);
            if (!BatchCommit) DataContext.SaveChanges();
                } catch(Exception ex)
                {
                    Trace.TraceError(ex.ToString());
                }
            return item;
        }
        
        public EventProcessorEventData Update(EventProcessorEventData item)
        {
            DataContext.Events.Attach(item);
            if (!BatchCommit) DataContext.SaveChanges();

            return item;
        }

        public void Delete(EventProcessorEventData item)
        {
            DataContext.Events.Remove(item);
            if (!BatchCommit) DataContext.SaveChanges();
        }

        public void Commit()
        {
            DataContext.SaveChanges();
        }

        public IEnumerator<EventProcessorEventData> GetEnumerator()
        {
            return DataContext.Events.AsQueryable().GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return DataContext.Events.AsQueryable().GetEnumerator();
        }

        public Type ElementType
        {
            get { return DataContext.Events.AsQueryable().ElementType; }
        }

        public System.Linq.Expressions.Expression Expression
        {
            get { return DataContext.Events.AsQueryable().Expression; }
        }

        public IQueryProvider Provider
        {
            get { return DataContext.Events.AsQueryable().Provider; }
        }

        public void Dispose()
        {
        }
    }
}
